package io.github.jesse205.transferstation.lite.helpers;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import android.service.quicksettings.TileService;

import io.github.jesse205.transferstation.lite.R;

public class PermissionsHelper {
    public static boolean askDrawOverlaysPermission(Activity activity, int requestCode) {
        boolean canDrawOverlays = Settings.canDrawOverlays(activity);
        if (!canDrawOverlays) {
            new AlertDialog.Builder(activity)
                    .setTitle(R.string.permission_ask)
                    .setMessage(R.string.permission_ask_drawOverlays)
                    .setPositiveButton(android.R.string.ok, (dialog, which) -> {
                        activity.startActivityForResult(getIntentToOverlaySettingActivity(activity), requestCode);
                    })
                    .setNegativeButton(android.R.string.no, null)
                    .show();
        }
        return canDrawOverlays;
    }

    public static boolean askDrawOverlaysPermissionInTile(TileService service) {
        boolean canDrawOverlays = Settings.canDrawOverlays(service);
        if (!canDrawOverlays) {
            AlertDialog.Builder builder = new AlertDialog.Builder(service)
                    .setTitle(R.string.permission_ask)
                    .setMessage(R.string.permission_ask_drawOverlays)
                    .setPositiveButton(android.R.string.ok, (dialog, which) -> {
                        service.startActivity(getIntentToOverlaySettingActivity(service));
                    })
                    .setNegativeButton(android.R.string.no, null);
            if (!service.isLocked())
                service.showDialog(builder.create());
        }
        return canDrawOverlays;
    }

    public static Intent getIntentToOverlaySettingActivity(Context context) {
        Uri uri = Uri.parse("package:" + context.getPackageName());
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, uri);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        return intent;
    }
}
